package com.joker.aigc.accountboolk.utils;


import com.alibaba.fastjson2.JSON;
import com.joker.aigc.accountboolk.domain.dto.AccountBookDTO;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: feixiang.li
 * @date: 2025-01-07 19:51
 */
@Slf4j
public class JsonUtils {

    private JsonUtils() {

    }

    public static <T> List<T> getJsonArray(String input, Class<T> clazz) {
        // 提取 JSON 部分
        Pattern pattern = Pattern.compile("\\[.*?\\]", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            String jsonString = matcher.group();
            try {
                List<T> o = JSON.parseArray(jsonString, clazz);
                return o;
            } catch (Exception e) {
                return null;
            }
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        String input = "根据您的输入，我将创建多个支出条目，因为吃黄焖鸡属于消费行为。以下是格式化后的数据输出：[{"
                + "\"type\": 2,"
                + "\"name\": \"黄焖鸡\","
                + "\"amount\": 20.0,"
                + "\"category\": \"餐饮\","
                + "\"date\": \"2024-10-02\""
                + "}, {"
                + "\"type\": 3,"
                + "\"name\": \"外卖\","
                + "\"amount\": 30.0,"
                + "\"category\": \"餐饮\","
                + "\"date\": \"2024-10-03\""
                + "}]";
        ;
        List<AccountBookDTO> json = getJsonArray(input, AccountBookDTO.class);
        log.info("json: {}", json);
    }
}
